#ifndef NETWORKMODULE_H
#define NETWORKMODULE_H

#include <QObject>
class DrunkSceneModel;
class QNetworkReply;
class QNetworkAccessManager;
class QTimer;
class QUrl;

class NetworkModule : public QObject
{
    Q_OBJECT
public:
    NetworkModule(QString url,int port,QObject *parent = 0);
    DrunkSceneModel* getModel(){return theModel;}
    QTimer* getTimer(){return loopTimer;}

    void startRequestLoop();
    void stopRequestLoop();
    void dropPendingReplies();

signals:
    //generic error signal
    void connectionError();
    //login and logout signals
    void loginSuccess();
    void loginFailure();
    void logoutSuccess();
    //updates in the challenge room for available players and pending challenges
    void playersAvailableForChallenge(QList<QString> players);
    void pendingChallengeFrom(QString);
    void noPendingChallenges();
    //signals to communicate updates in the challenges issued by tje player the so called "active challenges"
    void challengeDeliveredToPlayer(QString);
    void challengeDeliveryToPlayerFailed(QString);
    void challengeDeclined();
    //signifies that the map has been fetched and the network module is ready for gaming
    void readyForGameState();
    //signals to update game state
    void win(bool,int);
    void opponentAt(float);
private slots:
    void logoutRequest();
    void playersAvailableRequest();
    void checkForPendingChallengesRequest();
    void checkActiveChallengeStatusRequest();
    void gameStatusUpdateRequest();

    void challengeRoomRequests();
    void activeChallengeRequests();
    void gameplayRequests();

    void processReplies(QNetworkReply *);
    void parseReply(QNetworkReply *);
public slots:
    void attemptLogin(QString,QString);
    void challengePlayer(QString player);
    void cancelActiveChallengeRequest();
    void acceptChallengeBy(QString);
    void declineChallengeBy(QString);
private:
    void fetchMapRequest();
    void switchToActiveChallengeLoop();
    void switchToGameplayLoop();
    void switchToChallengeRoomLoop();

    QString opponent;
    QList<QNetworkReply *> processQueue;
    DrunkSceneModel *theModel;
    QTimer *loopTimer;
    QUrl *serverUrl;
    QNetworkAccessManager *networkAccessManager;    
};

#endif // NETWORKMODULE_H
